package com.zkadmin.controller;

import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Row;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.zkadmin.entity.SysUser;
import com.zkadmin.service.SysUserService;
import com.zkadmin.util.AdminConstants;

@SuppressWarnings("serial")
public class ResetUserPwdDialogCtrl extends BaseCtrl<Window> {
	@WireVariable
	private SysUserService sysUserService;

	@Wire
	private Window win;
	@Wire
	private Row oldPwdRow;

	@Wire
	private Textbox oldPassword;
	@Wire
	private Textbox password;

	private SysUser user;

	private boolean isCheckOldPwd = true;

	@Override
	protected void init(Window win) {
		this.win = win;

		Map<?, ?> args = Executions.getCurrent().getArg();
		if (args != null && !args.isEmpty()) {
			if (args.containsKey("userId")) {
				long userId = (Long) args.get("userId");
				user = sysUserService.findById(userId);
			}
		}

		if (user.getId() != sysUserService.getCurrentSysUser().getId()) {
			if (SecurityUtils.getSubject().hasRole(AdminConstants.ROLE_ADMIN) || SecurityUtils.getSubject().isPermitted("sys:user:reset_pwd")) {
				oldPwdRow.setVisible(false);
				isCheckOldPwd = false;
			}
		}
	}

	@Listen("onClick=#cancelBtn")
	public void closeDialog(Event e) {
		win.onClose();
	}

	@Listen("onClick=#okBtn")
	public void resetUserPwd(Event event) {
		if (isCheckOldPwd) {
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), oldPassword.getValue());
			try {
				subject.login(token);
			} catch (AuthenticationException e) {
				throw new WrongValueException(oldPassword, "\"旧密码错误，请确认！");
			}
		}
		sysUserService.changePassword(user.getId(), password.getValue());
		win.onClose();
	}

}
